

jQuery(function ($) {
	var user = JSON.parse(localStorage.getItem('user_info')) || {};
	var id = user.id;
	if (!id) {
		$('#myBalance').hide();
	}
	var balance = user.balance;
	//密码支付部分
	password();
	function password() {
		var _formPay = $('#form_paypsw');
		_formPay.validate({
			rules: {
				'payPassword_rsainput': {
					'minlength': 6,
					'maxlength': 6,
					required: true,
					digits: true,
					numPassword: true,
					echoNum: true
				}
			},
			messages: {
				'payPassword_rsainput': {
					'required': '<i class="icon icon-attention icon-lg"></i>&nbsp;请填写支付密码',
					'maxlength': '<i class="icon icon-attention icon-lg"></i>&nbsp;密码最多为{0}个字符',
					'minlength': '<i class="icon icon-attention icon-lg"></i>&nbsp;密码最少为{0}个字符',
					'digits': '<i class="icon icon-attention icon-lg"></i>&nbsp;密码只能为数字'
					// 'numPassword' : '<i class="icon icon-attention icon-lg"></i>&nbsp;连号不可用，相同数字不可用（如：123456，11111）',
					// 'echoNum' :'<i class="icon icon-attention icon-lg"></i>&nbsp;连号不可用，相同数字不可用（如：123456，11111）'		
				}
			},
			errorPlacement: function errorPlacement(error, element) {
				element.closest('div[data-error="i_error"]').append(error);
			},
			submitHandler: function submitHandler(form) {
				var _form = $(form);
				form.submit();
			}
		});
		var payPassword = $("#payPassword_container"),
		    _this = payPassword.find('i'),
		    k = 0,
		    j = 0,
		    password = '',
		    _cardwrap = $('#cardwrap');
		//点击隐藏的input密码框,在6个显示的密码框的第一个框显示光标
		payPassword.on('focus', "input[name='payPassword_rsainput']", function () {
			var _this = payPassword.find('i');
			if (payPassword.attr('data-busy') === '0') {
				//在第一个密码框中添加光标样式
				_this.eq(k).addClass("active");
				_cardwrap.css('visibility', 'visible');
				payPassword.attr('data-busy', '1');
			}
		});
		//change时去除输入框的高亮，用户再次输入密码时需再次点击
		payPassword.on('change', "input[name='payPassword_rsainput']", function () {
			_cardwrap.css('visibility', 'hidden');
			_this.eq(k).removeClass("active");
			payPassword.attr('data-busy', '0');
		}).on('blur', "input[name='payPassword_rsainput']", function () {

			_cardwrap.css('visibility', 'hidden');
			_this.eq(k).removeClass("active");
			payPassword.attr('data-busy', '0');
		});

		//使用keyup事件，绑定键盘上的数字按键和backspace按键
		payPassword.on('keyup', "input[name='payPassword_rsainput']", function (e) {

			var e = e ? e : window.event;

			//键盘上的数字键按下才可以输入
			if (e.keyCode == 8 || e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode >= 96 && e.keyCode <= 105) {

				k = this.value.length; //输入框里面的密码长度
				var l = _this.size(); //6

				for (; l--;) {

					//输入到第几个密码框，第几个密码框就显示高亮和光标（在输入框内有2个数字密码，第三个密码框要显示高亮和光标，之前的显示黑点后面的显示空白，输入和删除都一样）
					if (l === k) {
						_this.eq(l).addClass("active");
						_this.eq(l).find('b').css('visibility', 'hidden');
					} else {
						_this.eq(l).removeClass("active");
						_this.eq(l).find('b').css('visibility', l < k ? 'visible' : 'hidden');
					}

					if (k === 6) {
						j = 5;
					} else {
						j = k;
					}
					$('#cardwrap').css('left', j * 40 + 'px');
				}
			} else {
				//输入其他字符，直接清空
				var _val = this.value;
				this.value = _val.replace(/\D/g, '');
			}
		});
		//以上是密码支付部分
	}
	//解码
	var url = window.location.search;
	if (url) {
		var param;
		var totalPrice = 0; //应付金额，
		var order_sn; //订单号
		var order_type;
		var base = new Base64();
		//?切割字符串
		var valuesKey = url.split("=")[0];
		var values = url.split("=")[1];
		if (valuesKey == '?order_sn') {
			param = {
				"Order": {
					"order_sn": values
				}
			};
		} else {
			param = {
				"Order": {
					"id": values
				}
			};
		};
		send_ajax('post', '/get', param, function callback(data) {
			if (data.Order) {
				var user = JSON.parse(localStorage.getItem('user_info')) || {};
				var balance = user.balance;
				order_type = data.Order.order_type;
				if (data.Order.order_type == 1 && data.Order.paid_status == 0) {
					//是定制订单,还没有支付定金
					$('#order_msg').html('定制订单请支付定金');
					totalPrice = data.Order.deposit; //订单的金额
				} else if (data.Order.order_type == 1 && data.Order.paid_status == 1) {
					//定制订单，已经支付定金，准备支付尾款
					$('#order_msg').html('定制订单请支付尾款');
					totalPrice = keepTwoDecimalFull(data.Order.total_amt - data.Order.deposit); //订单的金额
				} else {
					totalPrice = keepTwoDecimalFull(data.Order.total_amt - data.Order.discount_amt); //订单的金额
				}
				order_sn = data.Order.order_sn; //订单号
				$('.order_id').html(order_sn);
				$('.payable').html(totalPrice);
				$('.y_balance_m').text(balance); //余额
				if (balance < data.Order.total_amt) {
					$('.combination_pay').show();
				} else {
					$('.combination_pay').hide();
				};

				if (balance == 0) {
					$('.balance').css('visibility', 'hidden');
				};
				$('.dropdown').click(function () {
					window.location.href="/user/order_details.html?order_id=" + data.Order.id
				});
			};
		});
	};
	getPayMethods(); //获取支付的方式
	function getPayMethods() {
		var param = {
			"PayType[]": {
				"PayType": {
					"use_flag": 1,
					"@column": "id,name,img,stages_flag,pay_code",
					"@order": "rank-"
				}
			}
		};
		send_ajax('post', '/get', param, function callback(data) {
			var html = "";
			var data = data['PayType[]'];
			for (var i = 0; i < data.length; i++) {
				html += '\n\t\t\t\t\t\t<li class="pay_item" >\n\t\t\t\t\t\t\t<span class="' + data[i].pay_code + '">' + data[i].name + '</span>\n\t\t\t\t\t\t\t<span class="' + (data[i].pay_code + '_step') + '">' + (data[i].stages_flag ? (data[i].name == '支付宝' ? '花呗' : data[i].name) + '分期' : '') + '</span>\n\t\t\t\t\t\t\t<div class="' + (data[i].pay_code + "_box") + ' hide">\n\t\t\t\t\t\t\t\t<ul class="j_ious_list ' + (data[i].pay_code + '_list') + '  clearfix">\n\t\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t</li>';
			}
			$('.pay_list').append(html);
			//选择支付方式的时候加上边框颜色
			$('.pay_item span').click(function () {

				if ($(this).hasClass('border_color')) {
					$(this).removeClass('border_color');
				} else {
					$('.pay_item span').removeClass('border_color');
					$(this).addClass('border_color');
				}
			});
		});
	}

	//事件冒泡
	$('.pay_list').click(function () {
		//京东支付
		if ($(event.target).hasClass('jd')) {
			var param = {
				orderSn: order_sn,
				user_id: id ? id : 0
			};
			//是否组合支付
			if ($('.balance').hasClass('yc_pay')) {
				param.balance_flag = 1;
			} else {
				param.balance_flag = 0;
			}
			//是否分期
			if ($('.j_ious_list_item').hasClass('border_color')) {
				param.fq_num = $('.j_ious_list_item.border_color').attr('data-plan');
			} else {
				param.fq_num = 0;
			};
			send_ajax('post', '/api/jdpay/jdpay', param, function callback(data) {
				if (data.code == 200) {
					$('.mask').show();
					var data = data.data;
					$("#jd input[ name='version' ] ").val(data.payOrderInfo.version);
					$("#jd input[ name='merchant' ] ").val(data.payOrderInfo.merchant);
					$("#jd input[ name='device' ] ").val(data.payOrderInfo.device);
					$("#jd input[ name='tradeNum' ] ").val(data.payOrderInfo.tradeNum);
					$("#jd input[ name='tradeName' ] ").val(data.payOrderInfo.tradeName);
					$("#jd input[ name='tradeDesc' ] ").val(data.payOrderInfo.tradeDesc);
					$("#jd input[ name='tradeTime' ] ").val(data.payOrderInfo.tradeTime);
					$("#jd input[ name='amount' ] ").val(data.payOrderInfo.amount);
					$("#jd input[ name='currency' ] ").val(data.payOrderInfo.currency);
					$("#jd input[ name='note' ] ").val(data.payOrderInfo.note);
					$("#jd input[ name='callbackUrl' ] ").val(data.payOrderInfo.callbackUrl);
					$("#jd input[ name='notifyUrl' ] ").val(data.payOrderInfo.notifyUrl);
					$("#jd input[ name='ip' ] ").val(data.payOrderInfo.ip);
					$("#jd input[ name='userType' ] ").val(data.payOrderInfo.userType);
					$("#jd input[ name='userId' ] ").val(data.payOrderInfo.userId);
					$("#jd input[ name='expireTime' ] ").val(data.payOrderInfo.expireTime);
					$("#jd input[ name='orderType' ] ").val(data.payOrderInfo.orderType);
					$("#jd input[ name='industryCategoryCode' ] ").val(data.payOrderInfo.industryCategoryCode);
					$("#jd input[ name='specCardNo' ] ").val(data.payOrderInfo.specCardNo);
					$("#jd input[ name='specId' ] ").val(data.payOrderInfo.specId);
					$("#jd input[ name='specName' ] ").val(data.payOrderInfo.specName);
					$("#jd input[ name='payChannel' ] ").val(data.payOrderInfo.payChannel);
					$("#jd input[ name='sign' ] ").val(data.payOrderInfo.sign);
					$("#jd input[ name='cert' ] ").val(data.payOrderInfo.cert);
					$("#jd input[ name='vendorId' ] ").val(data.payOrderInfo.vendorId);
					$("#jd input[ name='goodsInfo' ] ").val(data.payOrderInfo.goodsInfo);
					$("#jd input[ name='orderGoodsNum' ] ").val(data.payOrderInfo.orderGoodsNum);
					$("#jd input[ name='receiverInfo' ] ").val(data.payOrderInfo.receiverInfo);
					$("#jd input[ name='termInfo' ] ").val(data.payOrderInfo.termInfo);
					$("#jd input[ name='riskInfo' ] ").val(data.payOrderInfo.riskInfo);
					$("#jd input[ name='installmentNum' ] ").val(data.payOrderInfo.installmentNum);
					$("#jd input[ name='preProduct' ] ").val(data.payOrderInfo.preProduct);
					$('#jd').attr('action', data.payUrl);
					$('#jd').submit();
				}
			});
		} else if ($(event.target).hasClass('jd_step')) {
			$('.ali-pay_box').addClass('hide');
			//京东白条
			var jd_Html = "";
			var jdArr = [{ "plan": 3, "rate": 1, "firstPay": 0 }, { "plan": 6, "rate": 1, "firstPay": 0 }, { "plan": 12, "rate": 1, "firstPay": 0 }];
			for (var i = 0; i < jdArr.length; i++) {
				jdArr[i].total = keepTwoDecimalFull(totalPrice / jdArr[i].plan + totalPrice * jdArr[i].rate / 100);
				jdArr[i].fee = keepTwoDecimalFull(totalPrice * jdArr[i].rate / 100);
			};
			for (var k = 0; k < jdArr.length; k++) {
				jd_Html += '<li class="j_ious_list_item" data-plan="' + jdArr[k].plan + '">\n\t\t\t\t\t\t\t\t\t\t\t\t<strong>' + jdArr[k].total + "x" + jdArr[k].plan + '</strong>\n\t\t\t\t\t\t\t\t\t\t\t\t<p>\u542B\u670D\u52A1\u8D39' + jdArr[k].fee + '\u5143\uFF0C\u8D39\u7387' + parseFloat(jdArr[k].rate) + '%\u6708/\u8D77<p>\n\t\t\t\t\t\t\t\t\t\t</li>';
			};
			if ($(event.target).hasClass('border_color')) {
				$('.jd_box').removeClass('hide');
				$('.jd_list').html(jd_Html);
			} else {
				$('.jd_box').addClass('hide');
			};

			$('.jd_list .j_ious_list_item').click(function () {
				if ($(this).hasClass('border_color')) {
					$(this).removeClass('border_color');
				} else {
					$('.jd_list .j_ious_list_item').removeClass('border_color');
					$(this).addClass('border_color');
				}
			});
		} else if ($(event.target).hasClass('wx')) {
			//微信支付
			var param = {
				orderSn: order_sn,
				user_id: id ? id : 0
			};
			//是否组合支付
			if ($('.balance').hasClass('yc_pay')) {
				param.balance_flag = 1;
			} else {
				param.balance_flag = 0;
			}
			send_ajax('post', '/api/weixinpay/qcPay2', param, function callback(data) {
				if (data.code == 200) {
					$('.mask').show();
					window.location.href="/goods/weixin_pay.html?order_sn=" + order_sn + '&&' + "longUrl=" + data.data
					
				}
			});
		} else if ($(event.target).hasClass('ali-pay')) {
			//支付宝支付
			var param = {
				"orderSn": order_sn,
				"user_id": id ? id : 0
			};
			//是否组合支付
			if ($('.balance').hasClass('yc_pay')) {
				param.balance_flag = 1;
			} else {
				param.balance_flag = 0;
			}
			//是否分期
			if ($('.j_ious_list_item').hasClass('border_color')) {
				param.fq_num = $('.j_ious_list_item.border_color').attr('data-plan');
			} else {
				param.fq_num = 0;
			}
			var insertStr = function insertStr(soure, start, newStr) {
				return soure.slice(0, start) + newStr + soure.slice(start);
			};
			send_ajax('post', '/api/alipay/pcPay', param, function callback(data) {
				if (data.code == 200) {
					$('.mask').show();
					var data = data.data;
					data = insertStr(data, 6);
					$(document.body).prepend(data);
				}
			});
		} else if ($(event.target).hasClass('ali-pay_step')) {
			//花呗支付
			$('.jd_box').addClass('hide');
			var hbHtml = "";
			var hbArr = [{ "plan": 3, "rate": 2.30, "firstPay": 0 }, { "plan": 6, "rate": 4.50, "firstPay": 0 }, { "plan": 12, "rate": 7.50, "firstPay": 0 }];
			for (var i = 0; i < hbArr.length; i++) {
				hbArr[i].firstPay = keepTwoDecimalFull(totalPrice / hbArr[i].plan + totalPrice * hbArr[i].rate / 100 / hbArr[i].plan); //每期的费用
				hbArr[i].fee = keepTwoDecimalFull(totalPrice * hbArr[i].rate / 100 / hbArr[i].plan); //每期服务费
			};
			for (var k = 0; k < hbArr.length; k++) {
				hbHtml += '<li class="j_ious_list_item" data-plan=' + hbArr[k].plan + '>\n\t\t\t\t\t\t\t\t\t\t<strong>' + hbArr[k].firstPay + "x" + hbArr[k].plan + '</strong>\n\t\t\t\t\t\t\t\t\t\t<p>\u542B\u670D\u52A1\u8D39' + hbArr[k].fee + '\u5143/\u671F\uFF0C\u8D39\u7387' + parseFloat(hbArr[k].rate) + '%\u6708/\u8D77<p>\n\t\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t\t\t';
			};
			if ($(event.target).hasClass('border_color')) {
				$('.ali-pay_box').removeClass('hide');
				$('.ali-pay_list').html(hbHtml);
			} else {
				$('.ali-pay_box').addClass('hide');
			}
			$('.ali-pay_list .j_ious_list_item').click(function () {
				if ($(this).hasClass('border_color')) {
					$(this).removeClass('border_color');
				} else {
					$('.ali-pay_list .j_ious_list_item').removeClass('border_color');
					$(this).addClass('border_color');
				}
			});
		} else if ($(event.target).hasClass('kuaiqian')) {
			// 快钱支付
			var param = {
				orderSn: order_sn,
				user_id: id ? id : 0
			};
			//是否组合支付
			if ($('.balance').hasClass('yc_pay')) {
				param.balance_flag = 1;
			} else {
				param.balance_flag = 0;
			}
			send_ajax('post', '/api/kuaiqianpay/rmbPay', param, function callback(data) {
				if (data.code == 200) {
					$('.mask').show();
					var data = data.data;
					$("#kuaiqian input[ name='inputCharset' ] ").val(data.payOrderInfo.inputCharset);
					$("#kuaiqian input[ name='pageUrl' ] ").val(data.payOrderInfo.pageUrl);
					$("#kuaiqian input[ name='bgUrl' ] ").val(data.payOrderInfo.bgUrl);
					$("#kuaiqian input[ name='version' ] ").val(data.payOrderInfo.version);
					$("#kuaiqian input[ name='language' ] ").val(data.payOrderInfo.language);
					$("#kuaiqian input[ name='signType' ] ").val(data.payOrderInfo.signType);
					$("#kuaiqian input[ name='signMsg' ] ").val(data.signMsg);
					$("#kuaiqian input[ name='merchantAcctId' ] ").val(data.payOrderInfo.merchantAcctId);
					$("#kuaiqian input[ name='payerName' ] ").val(data.payOrderInfo.payerName);
					$("#kuaiqian input[ name='payerContactType' ] ").val(data.payOrderInfo.payerContactType);
					$("#kuaiqian input[ name='payerContact' ] ").val(data.payOrderInfo.payerContact);
					$("#kuaiqian input[ name='payerIdType' ] ").val(data.payOrderInfo.payerIdType);
					$("#kuaiqian input[ name='payerId' ] ").val(data.payOrderInfo.payerId);
					$("#kuaiqian input[ name='payerIP' ] ").val(data.payOrderInfo.payerIP);
					$("#kuaiqian input[ name='orderId' ] ").val(data.payOrderInfo.orderId);
					$("#kuaiqian input[ name='orderAmount' ] ").val(data.payOrderInfo.orderAmount);
					$("#kuaiqian input[ name='orderTime' ] ").val(data.payOrderInfo.orderTime);
					$("#kuaiqian input[ name='orderTimestamp' ] ").val(data.payOrderInfo.orderTimestamp);
					$("#kuaiqian input[ name='productName' ] ").val(data.payOrderInfo.productName);
					$("#kuaiqian input[ name='productNum' ] ").val(data.payOrderInfo.productNum);
					$("#kuaiqian input[ name='productId' ] ").val(data.payOrderInfo.productId);
					$("#kuaiqian input[ name='productDesc' ] ").val(data.payOrderInfo.productDesc);
					$("#kuaiqian input[ name='ext1' ] ").val(data.payOrderInfo.ext1);
					$("#kuaiqian input[ name='ext2' ] ").val(data.payOrderInfo.ext2);
					$("#kuaiqian input[ name='payType' ] ").val(data.payOrderInfo.payType);
					$("#kuaiqian input[ name='bankId' ] ").val(data.payOrderInfo.bankId);
					$("#kuaiqian input[ name='redoFlag' ] ").val(data.payOrderInfo.redoFlag);
					$("#kuaiqian input[ name='pid' ] ").val(data.payOrderInfo.pid);
					$('#kuaiqian').attr('action', data.payUrl);
					$('#kuaiqian').submit();
				}
			});
		}
	});
	//余额支付
	$('.balance').click(function () {
		if ($(this).hasClass('yc_pay')) {
			$(this).removeClass('yc_pay');
		} else {
			send_ajax('get', '/api/user/hadPayPassword?userId=' + id, '', function (data) {
				if (data.code == 200 && data.data) {
					if ($(this).hasClass('yc_pay')) {
						$(this).removeClass('yc_pay');
					} else {
						$('.shade').show();
					}
				} else {
					swal({
						text: "您还没有注册支付密码，请前往设置支付密码!",
						type: 'warning',
						showCancelButton: true,
						confirmButtonColor: '#3AD997',
						cancelButtonColor: '#EEE',
						confirmButtonText: '确定',
						cancelButtonText: '取消'
					}).then(function (isConfirm) {
						if (isConfirm) {
							window.location.href = "/user/pay_password.html";
						} else {}
					});
				}
			});
		}
	});
	//四舍五入
	function keepTwoDecimalFull(num) {
		var result = parseFloat(num);
		if (isNaN(result)) {
			alert('传递参数错误，请检查！');
			return false;
		}

		result = Math.round(num * 100) / 100;

		var s_x = result.toString();
		var pos_decimal = s_x.indexOf('.');
		if (pos_decimal < 0) {
			pos_decimal = s_x.length;
			s_x += '.';
		}
		while (s_x.length <= pos_decimal + 2) {
			s_x += '0';
		}
		return s_x;
	};
	$('.payment_sure').click(function () {
		var password = $('#payPassword_rsainput').val();
		if (password.length == 6) {
			var param = {
				pay_password: password,
				user_id: id ? id : 0,
			};
			send_ajax('post', '/api/user/confirmPayPassword', param, function (data) {
				if (data.code == 200 && data.data) {
					$('.balance').addClass('yc_pay');
					$('#payPassword_rsainput').val('');
					$('.sixDigitPassword-box b').css('visibility', 'hidden');
					$('#cardwrap').css('left', 0);
					if(balance<totalPrice){
						swal({
							text: "余额不足，需要组合支付!",
							type: 'warning',
							showCancelButton: true,
							confirmButtonColor: '#3AD997',
							cancelButtonColor: '#EEE',
							confirmButtonText: '确定',
							cancelButtonText: '取消'
						})
					}else{
					}
					
					$('.shade').hide();
				} else {
					$('#payPassword_rsainput').val('');
					$('.sixDigitPassword-box b').css('visibility', 'hidden');
					$('#cardwrap').css('left', 0);
					alert('密码错误，请重新输入！');
				}
			});
		} else {
			alert('请输入正确的密码！');
		}
	});
	$('.payment_cancel').click(function () {
		$('#payPassword_rsainput').val('');
		$('.sixDigitPassword-box b').css('visibility', 'hidden');
		$('#cardwrap').css('left', 0);
		$('.shade').hide();
	});
	$('.againChoose').click(function () {
		$('.mask').hide();
		$('.pay_tip').hide();
	});
});